// pages/messages/messages.js
Page({
  data: {
    activeTab: 'system',
    systemMessages: [],
    userMessages: [],
    baseUrl: 'http://localhost:3000',
    userInfo: null,
    loading: false
  },

  onLoad: function() {
    this.loadUserInfo().then(() => {
      this.loadMessages();
    });
  },

  onShow: function() {
    if (this.data.userInfo) {
      this.loadMessages();
    }
  },

  loadUserInfo: function() {
    return new Promise((resolve, reject) => {
      const userInfo = wx.getStorageSync('userInfo');
      if (userInfo) {
        this.setData({ userInfo }, () => {
          resolve();
        });
      } else {
        wx.redirectTo({
          url: '/pages/login/login'
        });
        reject(new Error('User info not found'));
      }
    });
  },

  loadMessages: function() {
    const { userInfo, activeTab } = this.data;
    if (!userInfo) return;

    this.setData({ loading: true });

    // 加载消息列表
    wx.request({
      url: `${this.data.baseUrl}/api/messages`,
      method: 'GET',
      data: {
        userId: userInfo.id,
        type: activeTab
      },
      success: (res) => {
        if (res.data) {
          // 处理消息时间格式
          const messages = res.data.map(msg => ({
            ...msg,
            created_at: this.formatTime(new Date(msg.created_at))
          }));

          // 根据消息类型设置数据
          if (activeTab === 'system') {
            this.setData({ systemMessages: messages });
          } else {
            // 加载发送者信息
            this.loadMessageSenders(messages);
          }
        }
      },
      fail: (err) => {
        console.error('获取消息列表失败:', err);
        wx.showToast({
          title: '获取消息失败',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  loadMessageSenders: function(messages) {
    // 确保只处理用户消息
    const userMessages = messages.filter(msg => msg.type === 'user');
    
    if (userMessages.length === 0) {
      this.setData({ userMessages: [] });
      return;
    }
  
    // 获取所有发送者的ID
    const senderIds = [...new Set(userMessages.map(msg => msg.sender_id))];
    
    // 批量获取用户信息
    Promise.all(senderIds.map(id => 
      new Promise((resolve) => {
        wx.request({
          url: `${this.data.baseUrl}/api/users/${id}`,
          success: (res) => resolve({ id, ...res.data }),
          fail: () => resolve({ id, username: '未知用户' })
        });
      })
    )).then(users => {
      // 创建用户ID到用户名的映射
      const userMap = {};
      users.forEach(user => {
        userMap[user.id] = user.username;
      });
  
      // 将用户名添加到消息中
      const messagesWithSenders = userMessages.map(msg => ({
        ...msg,
        sender_name: userMap[msg.sender_id] || '未知用户'
      }));
  
      this.setData({ userMessages: messagesWithSenders });
    }).catch(error => {
      console.error('加载发送者信息失败:', error);
      wx.showToast({
        title: '加载发送者信息失败',
        icon: 'none'
      });
    });
  },

  switchTab: function(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({ 
      activeTab: type
    }, () => {
      this.loadMessages();
    });
  },

  viewSystemMessage: function(e) {
    const { id } = e.currentTarget.dataset;
    // 更新消息状态为已读
    this.updateMessageStatus(id);
    
    // 如果是岗位通知，跳转到岗位详情
    const message = this.data.systemMessages.find(m => m.id === id);
    if (message && message.job_id) {
      wx.navigateTo({
        url: `/pages/job-detail/job-detail?id=${message.job_id}`
      });
    }
  },

  viewUserMessage: function(e) {
    const { id, sender } = e.currentTarget.dataset;
    // 更新消息状态为已读
    this.updateMessageStatus(id);
    
    // 跳转到聊天页面
    wx.navigateTo({
      url: `/pages/chat/chat?userId=${sender}`
    });
  },

  updateMessageStatus: function(messageId) {
    wx.request({
      url: `${this.data.baseUrl}/api/messages/${messageId}`,
      method: 'PUT',
      data: {
        status: 'read'
      },
      success: () => {
        // 重新加载消息列表
        this.loadMessages();
      }
    });
  },

  formatTime: function(date) {
    const now = new Date();
    const diff = now - date;
    const minute = 1000 * 60;
    const hour = minute * 60;
    const day = hour * 24;

    if (diff < minute) {
      return '刚刚';
    } else if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前';
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前';
    } else if (diff < day * 30) {
      return Math.floor(diff / day) + '天前';
    } else {
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${year}-${month}-${day}`;
    }
  }
});